var initialState=[];
var _=require('lodash');
function carts(state=initialState,action){
    //console.log(action.count);
    switch(action.type){
        case 'ADD_TO_CART':
        var pos=_.findIndex(state,{id:action.payload.id});
        //console.log(action.payload,'--------reducers');
        if(pos!==-1){
            state[pos].quantity=state[pos].quantity+action.count;
            return [...state];
        }else{
            action.payload.quantity=action.count;
            action.payload.checked=true;
            console.log(action.payload);
            return [...state,action.payload];
        }
        case 'DEL_TO_CART':
        var pos=_.findIndex(state,{id:action.payload.id});
        state.splice(pos,1);
        return [...state];
        case 'DEL_ALL_TO_CART':
        state.splice(0,state.length);
        return [...state];

        case 'CART_STATUS':
        var pos=_.findIndex(state,{id:action.payload.id});
        if(state[pos].checked==true){
            state[pos].checked=false;
        }else if(state[pos].checked==false){
            state[pos].checked=true;
        }
        return [...state];

        case 'CART_ALL_STATUS':
        console.log(state,action.payload);
        if(action.payload==true){
            for(var i=0;i<state.length;i++){
                state[i].checked=false;
            }
        }else{
            for(var i=0;i<state.length;i++){
                state[i].checked=true;
            }
        }
        return [...state];
        /* case 'TOTAL_NUM':
        var num=0;
        for(var i=0;i<state.length;i++){
            if(state[i].checked==true){
                num+=state[i].quantity;
            }
        }
        console.log(num);
        return [...state];

        case 'TOTAL_PRICE':
        var price=0;
        for(var i=0;i<state.length;i++){
            if(state[i].checked==true){
                price+=state[i].quantity*state[i].price;
            }
        }
        console.log(price);
        return [...state]; */

        default:
        return state;
    }
}

export default carts;